# -*- coding: utf-8 -*-
import base64
from binascii import a2b_hex

from Crypto.Cipher import AES
from Crypto.Util.Padding import pad


class PrpCrypt(object):
	def __init__(self, key="ZTE@FSSCZTE@FSSC"):
		self.key = key.encode('utf-8')
		self.mode = AES.MODE_ECB

	def pad_byte(self, b):
		return pad(b, AES.block_size)

	def encrypt(self, text):
		"""
		1 先生成aes实例
		2 对传入的text转成bytes
		3 对传入的text补全
		4 调用encrypt 加密 得到密文
		5 先将密文转16进制，在将16进制用base64转码，然后在将得到的base64解码

		\n:param text:
		:return:
		"""
		cryptor = AES.new(self.key, self.mode)
		text = text.encode('utf-8')
		text = self.pad_byte(text)
		ciphertext = cryptor.encrypt(text)
		cryptbase64 = base64.b64encode(ciphertext)
		cryptbase64 = cryptbase64.decode("utf-8")
		return cryptbase64

	def decrypt(self, text):
		"""
		解密和加密的顺序是相反的
		1 定义匿名函数，去掉补位
		2 base64解码
		3 生成aes实例
		4 16进制转2进制
		5 使用decrypt解码  得到补全的bytes类型明文

		\n:param text:
		:return:  解密且去掉补位的明文
		"""
		unpad = lambda s: s[:-ord(s[len(s) - 1:])]
		base64Str = base64.b64decode(text.encode('utf8'))
		cryptor = AES.new(self.key, self.mode)
		aesStr = cryptor.decrypt(a2b_hex(base64Str))
		aesStr = str(unpad(aesStr), encoding='utf8')
		return aesStr


cryptoObj = PrpCrypt()
